package com.daocao.ds.activity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.daocao.ds.R;
import com.daocao.ds.adapter.ManagerReportAdapter;
import com.daocao.ds.adapter.TabTopAdapter;
import com.daocao.ds.api.Api;
import com.daocao.ds.api.bean.LoanerLogBean;
import com.daocao.ds.api.bean.ManagerListBean;
import com.daocao.ds.api.model.LoanerIndexModel;
import com.daocao.ds.base.BaseActivity;
import com.daocao.ds.util.Network;
import com.daocao.ds.util.RxLifeUtil;
import com.daocao.ds.util.SelectTimeUtil;
import com.daocao.ds.util.Spans;
import com.daocao.ds.util.ToastUtil;
import com.daocao.ds.view.ObservableScrollView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class ManagerReportActivity extends BaseActivity implements ObservableScrollView.ScrollViewListener {

    @BindView(R.id.txt_month_profit)
    TextView txtMonthProfit;
    @BindView(R.id.txt_month_loan_money)
    TextView txtMonthLoanMoney;
    @BindView(R.id.txt_month_use)
    TextView txtMonthUse;
    @BindView(R.id.txt_month_return_money)
    TextView txtMonthReturnMoney;
    @BindView(R.id.tablayout)
    RecyclerView tablayout;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_right)
    TextView btnRight;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.txt_count_total)
    TextView txtCountTotal;
    @BindView(R.id.txt_count_no_repay)
    TextView txtCountNoRepay;
    @BindView(R.id.txt_count_repay)
    TextView txtCountRepay;
    @BindView(R.id.txt_count_overdue)
    TextView txtCountOverdue;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    private Unbinder unbiner;
    private ManagerReportAdapter adapter;
    private OptionsPickerView pickerView;
    private TabTopAdapter TabAdapter;
    private String date;
    //      "has_repay": 0，  //是否已回款，默认为 -1 ： -1 全部、 0 未回款、1 已回款
//              "is_overdue": 0，  //是否逾期，默认为-1 ： -1 全部、0 否、1-是
    private String has_repay = "1";
    private String is_overdue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager_report);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        scrollView.setScrollViewListener(this);
        TabAdapter = new TabTopAdapter(this);
        TabAdapter.setOnChooseListener(new TabTopAdapter.OnChooseListener() {
            @Override
            public void onClick(int poi) {
                currentPage = 1;
                if (poi == 0) {
                    has_repay = "1";
                    is_overdue = "";
                } else if (poi == 1) {
                    has_repay = "0";
                    is_overdue = "1";
                } else if (poi == 2) {
                    has_repay = "0";
                    is_overdue = "";
                }
                getManagerList(1);
            }
        });
        tablayout.setLayoutManager(new GridLayoutManager(this, 3));
        tablayout.setAdapter(TabAdapter);
        List<String> tab_titles = new ArrayList<>();
        tab_titles.add("已回款列表");
        tab_titles.add("已逾期列表");
        tab_titles.add("使用中列表");
        TabAdapter.update(tab_titles);


        Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(new Date().getTime());
        int year = mCalendar.get(Calendar.YEAR);
        int month = mCalendar.get(Calendar.MONTH);
        btnRight.setText(year + "/" + (month + 1));
        date = year + "" + (month + 1);
        pickerView = SelectTimeUtil.getTimeView(this, new SelectTimeUtil.DialogDefaultClickListener() {
            @Override
            public void confirm(String year, String month) {
                date = year + month;
                btnRight.setText(year + "/" + month);
                getLoanerIndex();
            }
        });

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getManagerList(currentPage);
            }
        });
        list.setNestedScrollingEnabled(false);
        adapter = new ManagerReportAdapter(this);
        list.setAdapter(adapter);

        getLoanerIndex();
        getManagerList(1);
    }

    public void getManagerList(int page) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        refresh.setRefreshing(true);
        ManagerListBean bean = new ManagerListBean();
        bean.page = page;
        bean.date = date;
        bean.has_repay = has_repay;
        bean.is_overdue = is_overdue;
        Api.api_service.getManagerList(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                        isOkRefresh = true;
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    adapter.add(result.datas, page == 1);
                    if (adapter.getItemCount() == 0) {
                        layoutEmpty.setVisibility(View.VISIBLE);
                    } else {
                        layoutEmpty.setVisibility(View.GONE);
                    }
                });
    }

    public void getLoanerIndex() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        refresh.setRefreshing(true);
        LoanerLogBean bean = new LoanerLogBean();
        bean.date = date;
        Api.api_service.getLoanerIndex(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    LoanerIndexModel.DatasBean item = result.datas;
                    txtMonthProfit.setText(item.month_profit);
                    txtMonthLoanMoney.setText(item.month_loans);
                    txtMonthReturnMoney.setText(item.month_repay);
                    txtMonthUse.setText(item.month_no_repay);


                    txtCountTotal.setText(getInfoText("放款总单数", item.count_total));
                    txtCountNoRepay.setText(getInfoText("使用中单数", item.count_no_repay));
                    txtCountRepay.setText(getInfoText("已回款单数", item.count_repay));
                    txtCountOverdue.setText(getInfoText("已逾期单数", item.count_overdue));
                });
    }

    private Spanned getInfoText(String one, String two) {
        return Spans.with(this).font(one, getResources().getDimensionPixelSize(R.dimen.x20), 0xffAAAAAA).
                font("\n" + two, getResources().getDimensionPixelSize(R.dimen.x28), 0xff333333).style(Typeface.BOLD).build();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_right:
                pickerView.show();
                break;
        }
    }

    private boolean isOkRefresh = false;
    private int currentPage = 1;

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (refresh != null) {
            refresh.setEnabled(scrollView.getScrollY() == 0);

        }

        if (y == (scrollView.getChildAt(0).getMeasuredHeight() - scrollView.getMeasuredHeight())) {
            //底部加载
            if (isOkRefresh) {
                isOkRefresh = false;
                currentPage++;
                getManagerList(currentPage);
            }
        }
    }
}
